package com.aos.iot.socket.common.channel;

import cn.hutool.core.util.StrUtil;
import com.aos.iot.socket.common.handler.AbstractHandlerFactor;
import com.aos.iot.socket.common.protocol.ProtocolFactor;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequiredArgsConstructor
public class CommonChannelInitializer extends ChannelInitializer<Channel> {

    private final ProtocolFactor protocolFactor;

    private final AbstractHandlerFactor abstractHandlerFactor;

    @Override
    protected void initChannel(Channel channel) {
        ChannelPipeline pipeline = channel.pipeline();
        protocolFactor.getProtocolMap().forEach((name, protocol) -> {
            pipeline.addLast(StrUtil.format("{}Decoder", name), protocol.decoder());
            pipeline.addLast(StrUtil.format("{}Encoder", name), protocol.encoder());
            pipeline.addLast(StrUtil.format("{}Handler", name), abstractHandlerFactor.getHandler(protocol.name()));
        });
    }
}
